import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../common/widgets.dart';

class ChannelTestPage extends StatefulWidget {
  @override
  ChannelTestSate createState() => ChannelTestSate();
}

class ChannelTestSate extends State<ChannelTestPage> {
  final MethodChannel _methodChannel = const MethodChannel('example.flutter.test/method_channel');
  final EventChannel _eventChannel = const EventChannel('example.flutter.test/event_channel');

  StreamSubscription<dynamic>? _streamSubscription;

  @override
  void initState() {
    _enableEventReceiver();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Channel测试'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0, bottom: 8.0),
          children: <Widget>[
            buildButton(context, '立即返回的MethodChannel请求', _callMethodChannelBackNow),
            buildButton(context, '延时返回的MethodChannel请求', _callMethodChannelBackDelay),
            // 异常测试Demo（专业版才会监控异常）
            // buildButton(context, 'no_plugin', () async {
            //   const MethodChannel methodChannel = MethodChannel('no_plugin');
            //   final int? result = await methodChannel.invokeMethod<int>('no_plugin');
            //   print('no_plugin: $result');
            // }),
            // buildButton(context, 'function_no_implemented', () async {
            //   final int? result = await _methodChannel.invokeMethod<int>('function_no_implemented');
            //   print('function_no_implemented: $result');
            // }),
            // buildButton(
            //     context, 'convert_error\n如：java侧返回String类型，Dart侧需要int类型', () async {
            //   final int? result = await _methodChannel.invokeMethod<int>('convert_error');
            //   print('convert_error: $result');
            // }),
            // buildButton(context, 'native_return_error', () async {
            //   final int? result = await _methodChannel.invokeMethod<int>('native_return_error');
            //   print('native_return_error: $result');
            // }),
            // buildButton(context, 'native_runtime_crash', () async {
            //   final int? result = await _methodChannel.invokeMethod<int>('native_runtime_crash');
            //   print('native_runtime_crash: $result');
            // }),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _disableEventReceiver();
    super.dispose();
  }

  void _enableEventReceiver() {
    _streamSubscription = _eventChannel.receiveBroadcastStream().listen(
        (dynamic event) => print('Flutter EventChannel Received event: $event'),
        onError: (dynamic error) => print('Flutter EventChannel Received error: ${error.message}'),
        onDone: () => print('Flutter EventChannel Received done'),
        cancelOnError: true);
  }

  void _disableEventReceiver() {
    _streamSubscription?.cancel();
    _streamSubscription = null;
  }

  Future<void> _callMethodChannelBackNow() async {
    const String method = 'method_now';
    try {
      print('Flutter MethodChannel start call method $method');
      final int result = (await _methodChannel.invokeMethod<int>(method))!;
      print('Flutter MethodChannel end call method $method, result: $result');
    } on PlatformException catch (e) {
      print('Flutter MethodChannel call method : $method error, error: ${e.toString()}');
    }
  }

  Future<void> _callMethodChannelBackDelay() async {
    const String method = 'method_delay';
    try {
      print('Flutter MethodChannel start call method $method');
      final int result = (await _methodChannel.invokeMethod<int>(method))!;
      print('Flutter MethodChannel end call method $method, result: $result');
    } on PlatformException catch (e) {
      print('Flutter MethodChannel call method : $method error, error: ${e.toString()}');
    }
  }
}
